package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@Api(tags = "c端-菜品浏览接口")
@RestController("UserDishController")
@RequestMapping("/user/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("根据分类id查询菜品")
    @GetMapping("/list")
    public Result<List<DishVO>> listResult( Long categoryId){
        log.info("缓存优化");
        //缓存优化
        //先判断redis中是否有缓存，查询数据库之前
        String key="div_"+categoryId;
List<DishVO>  list= (List<DishVO>) redisTemplate.opsForValue().get(key);
if(list !=null &&list.size()>0){
    return Result.success(list);
}
//没有就查询没mySQL数据库
        log.info("根据分类id查询菜品{}",categoryId);


        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);
        List<DishVO> voList = dishService.listDisVo(dish);
        //查询过后将查询的数据加入到缓存当中
        redisTemplate.opsForValue().set(key,voList);
        return Result.success(voList);
    }

}
